<template>
  <div class="app-container">
    <PageTools type="info">
      <template #before>
        <span>共{{ total }}条记录</span>
      </template>
      <template #after>
        <el-button size="small" type="warning" @click="$router.push('/import?type=user')">导入</el-button>
        <el-button size="small" type="danger" @click="handleExport">导出</el-button>
        <el-button size="small" type="primary" @click="handleAdd">新增员工</el-button>
      </template>
    </PageTools>
    <!-- 放置表格和分页 -->
    <el-card>
      <el-table v-loading="loading" border :data="list">
        <el-table-column label="序号" type="index" sortable="" width="80" />
        <el-table-column label="姓名" prop="username" />
        <el-table-column label="工号" prop="workNumber" />
        <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatterEmployment" />
        <el-table-column label="部门" prop="departmentName" />
        <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
          <template slot-scope="{row}">
            {{ row.timeOfEntry | formatDate }}
          </template>
        </el-table-column>
        <!-- formatDate -->
        <el-table-column label="账户状态" prop="enableState">
          <template slot-scope="{row}">
            <el-switch :value="row.enableState === 1" />
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="280">
          <template slot-scope="{row}">
            <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button type="text" size="small">角色</el-button>
            <el-button type="text" size="small" @click="handleDel(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-row type="flex" justify="end" align="middle" style="height: 60px">
        <el-pagination
          background
          :current-page.sync="page.page"
          :page-size.sync="page.size"
          :page-sizes="[2,5,10, 15,20]"
          layout="total, sizes, prev, pager, next"
          :total="total"
          @current-change="getEmployeeList"
          @size-change="getEmployeeList"
        />
      </el-row>
    </el-card>
    <addEmployee :dialog-visible.sync="dialogVisible" />
  </div>
</template>
<script>
import { getEmployeeListApi, delEmployeeApi } from '@/api/employees'
import employeesEnum from '@/api/constant/employees'
import addEmployee from './components/add-employee.vue'
export default {
  components: {
    addEmployee
  },
  data() {
    return {
      page: {
        page: 1,
        size: 10
      },
      list: [],
      total: 0,
      loading: false,
      dialogVisible: false
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      try {
        this.loading = true
        const { rows, total } = await getEmployeeListApi(this.page)
        this.list = rows
        this.total = total
      } finally {
        this.loading = false
      }
    },
    handleExport() {
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }

      import('@/vendor/Export2Excel').then(async excel => {
        // this.list [{
        //     "id": "604f764971f93f3ac8f365c2",
        //     "mobile": "13800000002",
        //     "username": "姜朋鸡",
        //     "password": "e10adc3949ba59abbe56e057f20f883e",
        //     "timeOfEntry": "2018-11-02",
        //     "formOfEmployment": 1,
        //     "workNumber": "9002",
        //     "correctionTime": "2018-11-30",
        //     "departmentName": "总裁办",
        // }]

        // Object.values(headers) ['username', 'mobile', 'timeOfEntry','formOfEmployment','correctionTime']

        // [["姜朋鸡", "13800000002", "2018-11-02"]]

        const { rows } = await getEmployeeListApi({ page: 1, size: this.total })
        const arr1 = rows.map(ele => {
          // ele
          const arr = []
          Object.values(headers).forEach(item => {
            // item  correctionTime2
            // arr.push(ele[item])
            if (item === 'timeOfEntry' || item === 'correctionTime') {
              // ele[item]
              // 过滤器
              arr.push(ele[item])
            } else if (item === 'formOfEmployment') {
              const obj = employeesEnum.hireType.find(ele1 => {
                return ele1.id === +ele[item]
              })
              arr.push(obj && obj.value || '非正式')
            }
          })
          return arr
        })
        console.log(arr1)

        // es6
        // Object.entries [[key, value]]
        // Object.values 取的值 value 1纬数组
        // Object.keys 取的键 key 1纬数组

        import('@/vendor/Export2Excel').then(excel => {
          excel.export_json_to_excel({
            header: Object.keys(headers), // 表头 必填  ['姓名', '手机号', '入职日期', '聘用形式']
            data: arr1, // 具体数据 必填 [['张三', '13399999', '2020-2020-2020', '正式']]
            filename: '员工', // 非必填
            autoWidth: true, // 非必填
            bookType: 'xlsx', // 非必填
            multiHeader: [['姓名', '主要信息', '', '', '', '', '']],
            merges: ['A1:A2', 'B1:G1']
          })
        })
      })
    },
    formatterEmployment(row, column, cellValue) {
      // console.log(cellValue)
      // console.log(employeesEnum.hireType)
      const obj = employeesEnum.hireType.find(ele => ele.id === +cellValue)
      return obj && obj.value || '非正式'
    },
    handleAdd() {
      this.dialogVisible = true
    },
    async handleDel(row) {
      // 需要id 作用域插槽 row.id
      // 二次确认
      try {
        await this.$confirm('确认删除该员工吗', '提示', {
          type: 'warning'
        })
        // 调用删除接口 封装 引入
        await delEmployeeApi(row.id)
        this.$message.success('删除成功')
        this.getEmployeeList()
      } catch (e) {
        // e s
      }
    }
  }
}
</script>
